package handler

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	jwt2 "github.com/golangblogs/gojwt"
	"im/api/request"
	"im/consts"
	"im/internal/dao"
	"im/internal/model"
	"im/pkg"
	"time"
)

func CreateUser(c *gin.Context) {
	var req request.CreateUserReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
			"data": err.Error(),
		})
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{
		Phone: req.Phone,
	}, &user)
	if user.Phone == req.Phone {
		c.JSON(200, gin.H{
			"code": 10001,
			"msg":  "用户已存在",
			"data": nil,
		})
		return
	}
	m := model.User{
		Phone:    req.Phone,
		Password: pkg.Md5(req.Password),
	}
	if !dao.Create(&m) {
		c.JSON(200, gin.H{
			"code": 10003,
			"msg":  "添加失败",
			"data": nil,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "注册成功",
		"data": m.Id,
	})
}
func LoginUser(c *gin.Context) {
	var req request.LoginUserReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
			"data": err.Error(),
		})
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{
		Phone: req.Phone,
	}, &user)
	if user.Phone != req.Phone {
		c.JSON(200, gin.H{
			"code": 10001,
			"msg":  "用户不存在",
			"data": nil,
		})
		return
	}
	if user.Password != pkg.Md5(req.Password) {
		c.JSON(200, gin.H{
			"code": 10002,
			"msg":  "密码错误",
			"data": nil,
		})
		return
	}
	token, _ := jwt2.NewJWT(consts.JWT_SELECT_KEY).CreateToken(jwt2.CustomClaims{
		ID: uint(user.Id),
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + 86400,
		},
	})
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": token,
	})
}

func ListUser(c *gin.Context) {
	var user []model.User
	dao.GetListByFields(&model.User{
		Id: uint64(c.GetUint("id")),
	}, &user)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表展示成功",
		"data": user,
	})
}
